<?php

namespace App\Store\Controllers\Financial\Goods;

use App\Common\Services\Common;
use App\Common\Services\CommonExcelExport;
use App\Common\Services\Store\Common as StoreCommon;
use App\Store\Models\Basic\GoodsCategory;
use App\Store\Models\Basic\GoodsStyle;
use App\Store\Models\Goods\GoodsStockList;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Store\Models\Account\SiteStore;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;

class GoodsStockNowController extends Controller
{
    public function getlist(Request $request)
    {
        $data = $this->getdata($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $data]);
    }

    public function doexport(Request $request)
    {
        $data = $this->getdata($request);
        if (!$data) {
            return response()->json(['code' => '001', 'msg' => '导出失败']);
        }

        $store_id = $request['store_ids'];
        $store_id = is_array($store_id) ? $store_id : (is_array(json_decode($store_id, true)) ? json_decode($store_id, true) : []);
        $store_names = SiteStore::whereIn('id', $store_id)->pluck('store_name')->toArray();


        $row = [

            ['goods_category_id' => '库存实时汇总'],
            ['goods_category_id' => '所属门店：' . join(',', $store_names)],
            [
                'goods_category_id' => '商品类别',
                'total_count' => '总件数',
                'total_piece_weight' => '总件重',
                'total_netglod_weight' => '总金重',
                'total_label_price' => '总标签价',
                'total_cost' => '总成本',
                'goods_style_id' => '款式',
                'count' => '件数',
                'piece_weight' => '件重',
                'netglod_weight' => '金重',
                'label_price' => '标签价',
                'cost' => '成本',
            ]];

        $is_store_account = StoreCommon::getIsStoreAccount($request);
        if (!$is_store_account) {
            unset($row[0]['total_cost']);
            unset($row[0]['cost']);
        }

        $total_count = $total_piece_weight = $total_netglod_weight = $total_label_price = $total_cost = $count = $piece_weight = $netglod_weight = $label_price = $cost = 0;
        $initcont = count($row) + 1;
        $mergecell = [];
        foreach ($data as $val) {
            $mergecell[] = 'A' . $initcont . ':A' . $initcont + count($val['goods_style_list']) - 1;
            $mergecell[] = 'B' . $initcont . ':B' . $initcont + count($val['goods_style_list']) - 1;
            $mergecell[] = 'C' . $initcont . ':C' . $initcont + count($val['goods_style_list']) - 1;
            $mergecell[] = 'D' . $initcont . ':D' . $initcont + count($val['goods_style_list']) - 1;
            $mergecell[] = 'E' . $initcont . ':E' . $initcont + count($val['goods_style_list']) - 1;
            $mergecell[] = 'F' . $initcont . ':F' . $initcont + count($val['goods_style_list']) - 1;
            $initcont = $initcont + count($val['goods_style_list']);
            foreach ($val['goods_style_list'] as $k1 => $v) {
                if ($k1 == 0) {
                    $exceldata[] = [
                        'goods_category_id' => $val['category_name'],
                        'total_count' => $val['count'],
                        'total_piece_weight' => $val['total_piece_weight'],
                        'total_netglod_weight' => $val['total_netglod_weight'],
                        'total_label_price' => $val['total_label_price'] / 100,
                        'total_cost' => $val['total_cost'] / 100,
                        'goods_style_id' => $v['style_name'],
                        'count' => $v['count'],
                        'piece_weight' => $v['total_piece_weight'],
                        'netglod_weight' => $v['total_netglod_weight'],
                        'label_price' => $v['total_label_price'] / 100,
                        'cost' => $v['total_cost'] / 100,
                    ];
                } else {
                    $exceldata[] = [
                        'goods_category_id' => is_numeric($val['category_name']) ? 0 : '',
                        'total_count' => is_numeric($val['count']) ? 0 : '',
                        'total_piece_weight' => is_numeric($val['total_piece_weight']) ? 0 : '',
                        'total_netglod_weight' => is_numeric($val['total_netglod_weight']) ? 0 : '',
                        'total_label_price' => is_numeric($val['total_label_price']) ? 0 : '',
                        'total_cost' => is_numeric($val['total_cost']) ? 0 : '',
                        'goods_style_id' => $v['style_name'],
                        'count' => $v['count'],
                        'piece_weight' => $v['total_piece_weight'],
                        'netglod_weight' => $v['total_netglod_weight'],
                        'label_price' => $v['total_label_price'] / 100,
                        'cost' => $v['total_cost'] / 100,
                    ];
                }


//                $total_count += $val['count'];
//                $total_piece_weight += $val['total_piece_weight'];
//                $total_netglod_weight += $val['total_netglod_weight'];
//                $total_label_price += $val['total_label_price'];
//                $total_cost += $v['total_cost'];
//                $count += $val['count'];
//                $piece_weight += $val['total_piece_weight'];
//                $netglod_weight += $val['total_netglod_weight'];
//                $label_price += $val['total_label_price'];
//                $cost += $v['total_cost'];
            }
        }

//        $exceldata[] = [
//            'goods_category_id' => '合计',
//            'total_count' => $total_count,
//            'total_piece_weight' => $total_piece_weight,
//            'total_netglod_weight' => $total_netglod_weight,
//            'total_label_price' => $total_label_price / 100,
//            'total_cost' => $total_cost / 100,
//            'goods_style_id' => '',
//            'count' => $count,
//            'piece_weight' => $piece_weight,
//            'netglod_weight' => $netglod_weight,
//            'label_price' => $label_price / 100,
//            'cost' => $cost / 100,
//        ];
//        $a = new CommonExcelExport($row, $exceldata);
//        dd($a);

        $filename = '库存实时汇总导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata, [], $mergecell), $filename);
    }

    public function doexportdetail(Request $request)
    {
        $request->is_stock = 2;
        $request->isgetall = 1;
        $list = GoodsStockList::getList($request)['list'];
        $list = Common::multiArraySort($list, 'goods_category_id', SORT_ASC);

        $store_id = $request['store_ids'];
        $store_id = is_array($store_id) ? $store_id : (is_array(json_decode($store_id, true)) ? json_decode($store_id, true) : []);
        $store_names = SiteStore::whereIn('id', $store_id)->pluck('store_name')->toArray();


        if (!$list) {
            return response()->json(['code' => '001', 'msg' => '导出失败']);
        }


        $row = [

            ['goods_sn_code' => '库存实时明细'],
            ['goods_sn_code' => '所属门店：' . join(',', $store_names)],
            [
                'goods_sn_code' => '条码',
                'stockin_at' => '入库日期',
                'supply_name' => '供应商',
                'goods_style_name' => '款式',
                'goods_name' => '品名',
                'goods_category_name' => '商品类别',
                'count' => '数量',
                'gramprice_fee' => '克销工费',
                'label_price' => '标签价',
                'pieceprice_fee' => '件销工费',
                'piece_weight' => '件重',
                'netglod_weight' => '金重',
                'content' => '含量',
                'costglod_price' => '成本金价',
                'costpiece_fee' => '件成本工费',
                'costgram_fee' => '克成本工费',
                'piececost_fee' => '单件成本',
                'goods_craft_name' => '工艺',
                'c_no' => '圈号',
                's_no' => '款号',
                'gemstone_fee1' => '宝石费1',
                'gemstone_fee2' => '宝石费2',
                'add_fee1' => '附加费1',
                'add_fee2' => '附加费2',
                'goods_brand_name' => '品牌',
                'cf_no' => '证书号',
                'cf_no_gia' => 'GIA证书号',
                'cf_fee' => '证书费',
                'main_stone_weigth' => '主石重',
                'main_stone_count' => '主石数',
                'other_stone_weigth' => '副石重',
                'other_stone_count' => '副石数',
                'color' => '颜色',
                'clarity' => '净度',
                'main_stone_val' => '主石值',
                'other_stone_val' => '副石值',
                'cut' => '切工',
                'goods_pricetype_name' => '价格类型',
                'goods_stone_name' => '石料材质',
                'procure_at' => '采购时间',
                'paytype_name' => '支付方式',
                'paymoney' => '应付账款',
                'remark' => '备注',
                'total_netglod_weight' => '总金重',
                'total_piece_weight' => '总件重',
                'is_code_more' => '是否一码多货'
            ]];
//dd($list);
        $exceldata = [];
        $count = $gramprice_fee = $label_price = $pieceprice_fee = $piece_weight = $netglod_weight = $costglod_price = $costpiece_fee = $costgram_fee = $piececost_fee = $gemstone_fee1 = $gemstone_fee2 = $add_fee1 = $add_fee2 = $cf_fee = $main_stone_weigth = $main_stone_count = $other_stone_weigth = $other_stone_count = $paymoney = $total_netglod_weight = $total_piece_weight = 0;
        foreach ($list as $val) {
            $exceldata[] = [
                'goods_sn_code' => $val['goods_sn_code'],
                'stockin_at' => $val['stockin_at'] > 0 ? date('Y-m-d H:i:s', $val['stockin_at']) : '',
                'supply_name' => $val['supply']['supply_name'] ?? '',
                'goods_style_name' => $val['goods_style']['style_name'] ?? '',
                'goods_name' => $val['goods_name'] ?? '',
                'goods_category_name' => $val['goods_category']['category_name'] ?? '',
                'count' => $val['count'],
                'gramprice_fee' => $val['gramprice_fee'] / 100,
                'label_price' => $val['label_price'] / 100,
                'pieceprice_fee' => $val['pieceprice_fee'] / 100,
                'piece_weight' => $val['piece_weight'],
                'netglod_weight' => $val['netglod_weight'],
                'content' => isset($val['goods_content']['content_name']) ? $val['goods_content']['content_name'] : '',
                'costglod_price' => $val['costglod_price'] / 100,
                'costpiece_fee' => $val['costpiece_fee'] / 100,
                'costgram_fee' => $val['costgram_fee'] / 100,
                'piececost_fee' => $val['piececost_fee'] / 100,
                'goods_craft_name' => isset($val['goods_craft']['craft_name']) ? $val['goods_craft']['craft_name'] : '',
                'c_no' => $val['c_no'],
                's_no' => $val['s_no'],
                'gemstone_fee1' => $val['gemstone_fee1'] / 100,
                'gemstone_fee2' => $val['gemstone_fee2'] / 100,
                'add_fee1' => $val['add_fee1'] / 100,
                'add_fee2' => $val['add_fee2'] / 100,
                'goods_brand_name' => isset($val['goods_brand']['brand_name']) ? $val['goods_brand']['brand_name'] : '',
                'cf_no' => $val['cf_no'],
                'cf_no_gia' => $val['cf_no_gia'],
                'cf_fee' => $val['cf_fee'] / 100,
                'main_stone_weigth' => $val['main_stone_weigth'],
                'main_stone_count' => $val['main_stone_count'],
                'other_stone_weigth' => $val['other_stone_weigth'],
                'other_stone_count' => $val['other_stone_count'],
                'color' => $val['color'],
                'clarity' => $val['clarity'],
                'main_stone_val' => $val['main_stone_val'],
                'other_stone_val' => $val['other_stone_val'],
                'cut' => $val['cut'],
                'goods_pricetype_name' => isset($val['goods_pricetype']['goods_pricetype_name']) ? $val['goods_pricetype']['goods_pricetype_name'] : '',
                'goods_stone_name' => isset($val['goods_stone']['goods_stone_name']) ? $val['goods_stone']['goods_stone_name'] : '',
                'procure_at' => $val['procure_at'] > 0 ? date('Y-m-d H:i:s', $val['procure_at']) : '',
                'paytype_name' => isset($val['paytype_info']['paytype_name']) ? $val['paytype_info']['paytype_name'] : '',
                'paymoney' => $val['paymoney'] / 100,
                'remark' => $val['remark'],
                'total_netglod_weight' => $val['total_netglod_weight'],
                'total_piece_weight' => $val['total_piece_weight'],
                'is_code_more' => $val['is_code_more'] == 1 ? '否' : '是',
            ];

        }

        $filename = '库存实时明细导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }

    public function getdata(Request $request)
    {
        $table_name = (new GoodsStockList())->getTable();
        $table_cate = (new GoodsCategory())->getTable();
        $table_style = (new GoodsStyle())->getTable();
        $where = [];

        //多选类别
        $store_id = $request['store_ids'];
        if ($store_id) {
            $store_id = is_array($store_id) ? $store_id : (is_array(json_decode($store_id, true)) ? json_decode($store_id, true) : []);
        }

        if (!empty($request['goods_brand_id'])) {
            $where[] = [$table_name . '.goods_brand_id', $request['goods_brand_id']];
        }

        if (!empty($request['goods_style_id'])) {
            $where[] = [$table_name . '.goods_style_id', $request['goods_style_id']];
        }

        if (!empty($request['goods_brand_id'])) {
            $where[] = [$table_name . '.goods_brand_id', $request['goods_brand_id']];
        }

        $goods_cabinetgroup_id = (int)$request['goods_cabinetgroup_id'];

        //多选类别
        $goods_category_id = $request['goods_category_ids'] ?? '';
        $goods_category_ids = [];
        if ($goods_category_id) {
            $goods_category_ids = is_array($goods_category_id) ? $goods_category_id : (is_array(json_decode($goods_category_id, true)) ? json_decode($goods_category_id, true) : []);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $query = Db::table($table_name)
            ->join('site_basic_goods_category', $table_name . '.goods_category_id', '=', 'site_basic_goods_category.id')
            ->where([
                    $table_name . '.cp_id' => $cp_id,
                    $table_name . '.is_del' => 1,
                    $table_cate . '.is_del' => 1
                ] + $where);
        if (!empty($goods_cabinetgroup_id)) {
            $query->where('site_basic_goods_category.goods_cabinetgroup_id', $goods_cabinetgroup_id);
        }
        if (!empty($goods_category_ids)) {
            $query->whereIn($table_name . '.goods_category_id', $goods_category_ids);
        }
        if (!empty($store_id)) {
            $query->whereIn($table_name . '.store_id', $store_id);
        }

        $store_ids = StoreCommon::getCurrentAccountStoreId($request);
        if ($store_ids) { //权限控制
            if (is_array($store_ids)) { //获取当前权限下的门店
                $query->whereIn($table_name . '.store_id', $store_ids);
            }
            if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                $query->where($table_name . '.store_id', intval($store_ids));
            }
        }
        $query->select($table_name . '.goods_category_id', 'site_basic_goods_category.category_name', $table_name . '.pricetype', DB::raw('sum(count) as count, sum(count*piece_weight) as total_piece_weight, sum(total_netglod_weight) as total_netglod_weight, sum(count*label_price) as total_label_price'));
        $list = $query->where('count', '>', 0)
            ->groupBy($table_name . '.goods_category_id')
            ->get()
            ->toArray();

        $data = [];
        if ($list) {
            foreach ($list as $k => $item) {
                $data[$k] = json_decode(json_encode($item, true), true);
                $query1 = Db::table($table_name)->where([
                        'cp_id' => $cp_id,
                        'is_del' => 1,
                        'goods_category_id' => $item->goods_category_id
                    ] + $where);

                if (!empty($store_id)) {
                    $query1->whereIn($table_name . '.store_id', $store_id);
                }

                if ($store_ids) { //权限控制
                    if (is_array($store_ids)) { //获取当前权限下的门店
                        $query1->whereIn($table_name . '.store_id', $store_ids);
                    }
                    if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                        $query1->where($table_name . '.store_id', intval($store_ids));
                    }
                }

                $query1->select('goods_category_id', DB::raw('sum(total_cost_fee) as total_cost'));
                $res1 = $query1->where('count', '>', 0)->groupBy('goods_category_id')->first();
                $data[$k]['total_cost'] = $res1->total_cost;

                // 款式
                $query2 = Db::table($table_name)
                    ->join('site_basic_goods_style', $table_name . '.goods_style_id', '=', 'site_basic_goods_style.id')
                    ->where([
                            $table_name . '.cp_id' => $cp_id,
                            $table_name . '.is_del' => 1,
                            $table_name . '.goods_category_id' => $item->goods_category_id,
                            $table_style . '.is_del' => 1
                        ] + $where);

                if (!empty($store_id)) {
                    $query2->whereIn($table_name . '.store_id', $store_id);
                }

                if ($store_ids) { //权限控制
                    if (is_array($store_ids)) { //获取当前权限下的门店
                        $query2->whereIn($table_name . '.store_id', $store_ids);
                    }
                    if (is_numeric($store_ids) && intval($store_ids) > 0) { //获取当前门店下的列表
                        $query2->where($table_name . '.store_id', intval($store_ids));
                    }
                }
                $res2 = $query2->where($table_name . '.count', '>', 0)
                    ->select($table_name . '.goods_style_id', 'site_basic_goods_style.style_name', DB::raw('sum(count) as count, sum(count*piece_weight) as total_piece_weight, sum(total_netglod_weight) as total_netglod_weight, sum(count*label_price) as total_label_price, sum(total_cost_fee) as total_cost'))
                    ->groupBy($table_name . '.goods_style_id')
                    ->get()
                    ->toArray();
                $data[$k]['goods_style_list'] = [];
                if ($res2) {
                    foreach ($res2 as $k2 => $v2) {
                        $v2 = json_decode(json_encode($v2, true), true);
                        $data[$k]['goods_style_list'][$k2] = json_decode(json_encode($v2, true), true);

                    }
                }
            }
        }



        // 过滤虚拟的数据
        $virtuallyCate =GoodsCategory::query()
            ->where(['cp_id'=>$cp_id,'is_del'=>1,'is_virtually'=>1])
            ->when(!empty($store_ids),function($query) use ($store_ids){
                if(is_array($store_ids)){
                    $query->whereIn('store_id',$store_ids);
                }else{
                    $query->where('store_id',$store_ids);
                }
            })
            ->get(['id'])
            ->pluck('id')
            ->toArray();

        $groupData = [];
        foreach ($data as &$val) {
            if(!in_array($val['goods_category_id'],$virtuallyCate)){
                $val['total_piece_weight'] =  $val['total_piece_weight']*1000;
                $val['total_netglod_weight'] =  $val['total_netglod_weight']*1000;
                $groupData[$val['category_name']][] = $val;
            }

        }

        $newData = [];
        foreach ($groupData as &$group) {
            $data = [];
            $data['goods_category_id'] = array_column($group, 'goods_category_id');
            $data['category_name'] = $group[0]['category_name'];
            $data['pricetype'] = $group[0]['pricetype'];
            $data['count'] = array_sum(array_column($group, 'count'));
            $data['total_piece_weight'] = bcdiv(array_sum(array_column($group, 'total_piece_weight')), 1000, 3);
            $data['total_netglod_weight'] =  bcdiv(array_sum(array_column($group, 'total_netglod_weight')), 1000, 3);
            $data['total_label_price'] = array_sum(array_column($group, 'total_label_price'));
            $data['total_cost'] = array_sum(array_column($group, 'total_cost'));
            $dgoods_style_list = array_merge(...array_column($group, 'goods_style_list'));

            $styleArr = [];
            foreach ($dgoods_style_list as $style) {
                $styleArr[$style['style_name']][] = $style;
            }
            
            $styleData = [];
            foreach ($styleArr as $st) {
                $styleData[] = [
                    'goods_style_id' => array_column($st, 'goods_style_id'),
                    'style_name' => $st[0]['style_name'],
                    'count' => array_sum(array_column($st, 'count')),
                    'total_piece_weight' => array_sum(array_column($st, 'total_piece_weight')),
                    'total_netglod_weight' => array_sum(array_column($st, 'total_netglod_weight')),
                    'total_label_price' => array_sum(array_column($st, 'total_label_price')),
                    'total_cost' => array_sum(array_column($st, 'total_cost')),
                ];
            }
            $data['goods_style_list'] =$styleData;
           $newData[] = $data;
        }

        return $newData;
    }

    public function detail(Request $request)
    {
        $request->isgetall = 0;
        $request->is_stock = 2;
        $data = GoodsStockList::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $data]);
    }

    public function detailexport(Request $request)
    {
        $request->isgetall = 1;
        $request->is_stock = 2;
        $data = GoodsStockList::getList($request);
        if (!$data['list']) {
            return response()->json(['code' => '001', 'msg' => '导出失败']);
        }

        $store_id = $request['store_ids'];
        $store_id = is_array($store_id) ? $store_id : (is_array(json_decode($store_id, true)) ? json_decode($store_id, true) : []);
        $store_names = SiteStore::whereIn('id', $store_id)->pluck('store_name')->toArray();

        $row = [
            [
                'goods_sn_code' => '条码',
                'goods_name' => '品名',
                'goods_category_id' => '商品类别',
                'goods_style_id' => '款式',
                'count' => '数量',
                'total_piece_weight' => '件重',
                'total_netglod_weight' => '金重',
                'cf_no' => '证书号',
                's_no' => '款号',
                'c_no' => '圈号',
                'main_stone_weigth' => '主石重',
                'other_stone_weigth' => '副石重',
                'color' => '颜色',
                'clarity' => '净度',
                'label_price' => '标签价',
                'gramprice_fee' => '克销工费',
                'pieceprice_fee' => '件销工费',
                'goods_brand_id' => '品牌',
                'goods_pricetype_id' => '价格类型',
                'store_id' => '所属门店',
                'stockin_at' => '入库时间',
                'create_at' => '创建时间',
            ]];

        $exceldata = [];
        foreach ($data['list'] as $val) {
            $exceldata[] = [
                'goods_sn_code' => $val['goods_sn_code'],
                'goods_name' => $val['goods_name'],
                'goods_category_id' => $val['goods_category']['category_name'] ?? '',
                'goods_style_id' => $val['goods_style']['style_name'] ?? '',
                'count' => $val['count'],
                'total_piece_weight' => $val['total_piece_weight'],
                'total_netglod_weight' => $val['total_netglod_weight'],
                'cf_no' => $val['cf_no'],
                's_no' => $val['s_no'],
                'c_no' => $val['c_no'],
                'main_stone_weigth' => $val['main_stone_weigth'],
                'other_stone_weigth' => $val['other_stone_weigth'],
                'color' => $val['color'],
                'clarity' => $val['clarity'],
                'label_price' => $val['label_price'] / 100,
                'gramprice_fee' => $val['gramprice_fee'] / 100,
                'pieceprice_fee' => $val['pieceprice_fee'] / 100,
                'goods_brand_id' => $val['goods_brand']['brand_name'] ?? '',
                'goods_pricetype_id' => $val['goods_pricetype']['pricetype_name'] ?? '',
                'store_id' => $val['storeinfo']['store_name'] ?? '',
                'stockin_at' => date('Y-m-d H:i:s', $val['stockin_at']),
                'create_at' => date('Y-m-d H:i:s', $val['create_at']),
            ];
        }

        $filename = '库存实时详情导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);
    }
}
